package dq.study.shiro.authentication;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.pam.AuthenticationStrategy;
import org.apache.shiro.realm.Realm;

import java.util.Collection;

/**
 * @author dongqun
 * @date 2020/4/10 11:10
 */
public class CustomAuthenticationStrategy implements AuthenticationStrategy {
    @Override
    public AuthenticationInfo beforeAllAttempts(Collection<? extends Realm> realms, AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = (String) usernamePasswordToken.getUsername();
        String password = (String) new String(usernamePasswordToken.getPassword());
        for (Realm realm : realms) {
            return realm.getAuthenticationInfo(token);
        }
        return null;
    }

    @Override
    public AuthenticationInfo beforeAttempt(Realm realm, AuthenticationToken token, AuthenticationInfo aggregate) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = (String) usernamePasswordToken.getUsername();
        String password = (String) new String(usernamePasswordToken.getPassword());
        return realm.getAuthenticationInfo(token);
    }

    @Override
    public AuthenticationInfo afterAttempt(Realm realm, AuthenticationToken token, AuthenticationInfo singleRealmInfo, AuthenticationInfo aggregateInfo, Throwable t) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = (String) usernamePasswordToken.getUsername();
        String password = (String) new String(usernamePasswordToken.getPassword());
        return realm.getAuthenticationInfo(token);

    }

    @Override
    public AuthenticationInfo afterAllAttempts(AuthenticationToken token, AuthenticationInfo aggregate) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = (String) usernamePasswordToken.getUsername();
        String password = (String) new String(usernamePasswordToken.getPassword());

        UsernamePasswordToken usernamePasswordToken2 = (UsernamePasswordToken) aggregate;
        String username2 = (String) usernamePasswordToken2.getUsername();
        String password2 = (String) new String(usernamePasswordToken2.getPassword());

        return aggregate;
    }
}
